<template>
  <div class="discussion-create-container">
    <div class="create-header">
      <h1>发布新讨论</h1>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="discussion-form"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入讨论标题"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="10"
          placeholder="请输入讨论内容"
          maxlength="2000"
          show-word-limit
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="loading">
          发布讨论
        </el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { sendDiscussion } from '../api/discussion';

const router = useRouter();
const formRef = ref<FormInstance>();
const loading = ref(false);

// 表单数据
const form = reactive({
  title: '',
  content: ''
});

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入讨论标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入讨论内容', trigger: 'blur' },
    { min: 10, max: 2000, message: '内容长度在 10 到 2000 个字符之间', trigger: 'blur' }
  ]
});

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const result = await sendDiscussion({
          title: form.title,
          content: form.content
        });
        
        if (result.code === 0) {
          ElMessage.success('发布成功');
          router.push('/discussions');
        } else {
          ElMessage.error(result.msg || '发布失败');
        }
      } catch (error) {
        console.error('发布讨论失败:', error);
        ElMessage.error('发布失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 返回上一页
const goBack = () => {
  router.back();
};
</script>

<style scoped>
.discussion-create-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.create-header {
  margin-bottom: 30px;
}

.create-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.discussion-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}
</style> 